package com.aihome.springbootjwt.interceptor;

import com.aihome.springbootjwt.annotation.PassToken;
import com.aihome.springbootjwt.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @ClassName LoginInterceptor
 * @Description 登录拦截器
 * @Author zhangjigang
 * @Date 2021/3/23 18:29
 * @Version 1.0.0
 */
@Slf4j
@Component
public class LoginTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        // 从请求头中取出 token  这里需要和前端约定好把jwt放到请求头一个叫token的地方
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        } else {
            log.info("token拦截需要验证");
            // 执行认证
            log.info("token:{}", token);
            if (null == token || !JwtUtil.verifyToken(token)) {
                response.getWriter().write("token校验失败");
                return false;
            }
            // 获取 token 中的 user Name
            //获取载荷内容
            String userId = JwtUtil.getAudience(token);
            String userName = JwtUtil.getClaimByName(token, "userName").asString();
            //放入attribute以便后面调用
            request.setAttribute("userId", userId);
            request.setAttribute("userName", userName);
            return true;
        }
        response.getWriter().write("token校验失败");
        return false;
    }
}
